package com.geeyuu.android.databases;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.geeyuu.android.activity.MainTabActivity;
import com.geeyuu.android.model.BaseUserInfo;
import com.geeyuu.android.model.ChatInfo;
import com.geeyuu.android.utils.DBUtil;

public class DataBaseHelper {

    private static GeeSQLite mGeeSQLite;
    private static SQLiteDatabase mSqLiteDatabase;

    private synchronized static void initDB(Context context) {
        if (null == mGeeSQLite || mGeeSQLite.isClosed()) {
            mGeeSQLite = new GeeSQLite(context, null, null, 0);
        }
        if (null == mSqLiteDatabase || !mSqLiteDatabase.isOpen()) {
            mSqLiteDatabase = mGeeSQLite.getWritableDatabase();
        }
    }
    
    public static Cursor getChatInfo(Context context, long uid){
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return null;
            }
            Cursor c = mSqLiteDatabase.query(ChatInfo.TABLE_NAME, null, ChatInfo.FRIEND_UID + "=?", new String[]{String.valueOf(uid)}, null, null, ChatInfo.SEND_DATE + " ASC");
            if(null != c){
                return c;
            }
            return null;
        }
    }
    
    public static long saveChatInfo(Context context, ContentValues cv){
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return -1;
            }
            return mSqLiteDatabase.insert(ChatInfo.TABLE_NAME, null, cv);
        }
    }
    
    public static boolean updateChatInfo(Context context, ContentValues cv, int chatId){
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return false;
            }
            long effectRow = mSqLiteDatabase.update(ChatInfo.TABLE_NAME, cv, ChatInfo.CHAT_ID + "=?", new String[]{String.valueOf(chatId)});
            if(effectRow > 0){
                return true;
            }
            return false;
        }
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    public static boolean saveUserInfo(Context context, ContentValues cv) {
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return false;
            }
            if (mSqLiteDatabase.insert(BaseUserInfo.TABLE_NAME, null, cv) == -1) {
                if(!MainTabActivity.isAppShowing){
                    close();
                }
                return false;
            } else {
                if(!MainTabActivity.isAppShowing){
                    close();
                }
                return true;
            }
        }
    }

    public static boolean isUserExist(Context context, long uid) {
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return false;
            }
            Cursor c = mSqLiteDatabase.rawQuery("SELECT " + BaseUserInfo.EXTRA_UID + " FROM " + BaseUserInfo.TABLE_NAME
                    + " WHERE " + BaseUserInfo.EXTRA_UID + "=?", new String[]{String.valueOf(uid)});
            if (c != null && c.getCount() == 1) {
                if(!MainTabActivity.isAppShowing){
                    close();
                }
                return true;
            }
        }
        if(!MainTabActivity.isAppShowing){
            close();
        }
        return false;
    }

    public static boolean updateUserInfo(Context context, ContentValues cv, long uid) {
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return false;
            }
            if (mSqLiteDatabase.update(BaseUserInfo.TABLE_NAME, cv, BaseUserInfo.EXTRA_UID + "=?", new String[]{String.valueOf(uid)}) > 0) {
                if(!MainTabActivity.isAppShowing){
                    close();
                }
                return true;
            } else {
                if(!MainTabActivity.isAppShowing){
                    close();
                }
                return false;
            }
        }
    }
    
    public static boolean saveOrUpdateUserBatch(Context context, ContentValues... cvs){
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return false;
            }
            mSqLiteDatabase.beginTransaction();
            try{
                if(null != cvs){
                    int size = cvs.length;
                    if(size > 0){
                        for(int i=0; i<size; i++){
                            ContentValues cv = cvs[i];
                            long uid = cv.getAsLong(BaseUserInfo.EXTRA_UID);
                            Cursor c = mSqLiteDatabase.query(BaseUserInfo.TABLE_NAME, new String[]{BaseUserInfo.EXTRA_UID}, BaseUserInfo.EXTRA_UID + "=?", new String[]{String.valueOf(uid)}, null, null, null);
                            if(c != null && c.getCount() == 1){ //update
                                mSqLiteDatabase.update(BaseUserInfo.TABLE_NAME, cv, BaseUserInfo.EXTRA_UID + "=?", new String[]{String.valueOf(uid)});
                            }else{ //insert
                                mSqLiteDatabase.insert(BaseUserInfo.TABLE_NAME, null, cvs[i]);
                            }
                            c.close();
                        }
                    }else{
                        if(!MainTabActivity.isAppShowing){
                            close();
                        }
                        return false;
                    }
                }else{
                    if(!MainTabActivity.isAppShowing){
                        close();
                    }
                    return false;
                }
                mSqLiteDatabase.setTransactionSuccessful();
            }finally{
                mSqLiteDatabase.endTransaction();
            }
        }
        if(!MainTabActivity.isAppShowing){
            close();
        }
        return true;
    }

    public static Cursor getAroundUserCursor(Context context, int limit, int orderByCode, int roleCode, int onlineCode) {
        String oderByStr = null;
        if(orderByCode == BaseUserInfo.ORDER_BY_POP_VALUE){
            oderByStr = BaseUserInfo.EXTRA_POP_VALUE + " DESC";
        }else if(orderByCode == BaseUserInfo.ORDER_BY_DISTANCE){
            oderByStr = BaseUserInfo.EXTRA_DISTANCE + " ASC";
        }
        
        StringBuilder sb = new StringBuilder();
        String selection = null;
        
        if(roleCode == BaseUserInfo.ROLE_0){
            selection = BaseUserInfo.EXTRA_ROLE + "=?";
            sb.append(BaseUserInfo.ROLE_0);
        }else if(roleCode == BaseUserInfo.ROLE_1){
            selection = BaseUserInfo.EXTRA_ROLE + "=?";
            sb.append(BaseUserInfo.ROLE_1);
        }else if(roleCode == BaseUserInfo.ROLE_05){
            selection = BaseUserInfo.EXTRA_ROLE + "=?";
            sb.append(BaseUserInfo.ROLE_05);
        }
        
        if(onlineCode == BaseUserInfo.USER_ONLINE){
            if(null != selection){
                selection = selection + " AND " + BaseUserInfo.EXTRA_IS_ONLINE + "=?";
                sb.append("," + BaseUserInfo.USER_ONLINE);
            }else{
                selection = BaseUserInfo.EXTRA_IS_ONLINE + "=?";
                sb.append(BaseUserInfo.USER_ONLINE);
            }
        }
        
        String[] args = selection != null ? sb.toString().split(",") : null;
        
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return null;
            }
            Cursor c = mSqLiteDatabase.query(BaseUserInfo.TABLE_NAME, BaseUserInfo.SELECTION_AROUND_COLUMN,
                    selection, args, null, null, oderByStr, String.valueOf(limit));
            if (null != c) {
                if (c.getCount() > 0) {
                    return c;
                }
            }
        }
        if(!MainTabActivity.isAppShowing){
            close();
        }
        return null;
    }

    public static BaseUserInfo getUserInfo(Context context, long uid) {
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return null;
            }
            BaseUserInfo userInfo = null;
            Cursor c = mSqLiteDatabase.query(BaseUserInfo.TABLE_NAME, null, BaseUserInfo.EXTRA_UID + "=?", new String[]{String.valueOf(uid)}, null, null, null);
            if (null != c) {
                if (c.getCount() == 1 && c.moveToFirst()) {
                    userInfo = new BaseUserInfo();
                    userInfo.age = DBUtil.getInt(c, BaseUserInfo.EXTRA_AGE);
                    userInfo.distance = DBUtil.getString(c, BaseUserInfo.EXTRA_DISTANCE);
                    userInfo.height = DBUtil.getInt(c, BaseUserInfo.EXTRA_HEIGHT);
                    userInfo.isGuest = DBUtil.getInt(c, BaseUserInfo.EXTRA_IS_GUEST);
                    userInfo.isOnline = DBUtil.getInt(c, BaseUserInfo.EXTRA_IS_ONLINE);
                    userInfo.lastAlbumModifyTime = DBUtil.getLong(c, BaseUserInfo.EXTRA_LAST_ALBUM_MODIFY_TIME);
                    userInfo.lastOnlineTime = DBUtil.getInt(c, BaseUserInfo.EXTRA_LAST_ONLINE_TIME);
                    userInfo.lastModifyTime = DBUtil.getLong(c, BaseUserInfo.EXTRA_LAST_MODIFY_TIME);
                    userInfo.lonAndlat = DBUtil.getString(c, BaseUserInfo.EXTRA_LON_AND_LAT);
                    userInfo.mainPhotoID = DBUtil.getString(c, BaseUserInfo.EXTRA_MAIN_PHOTO_ID);
                    userInfo.nickName = DBUtil.getString(c, BaseUserInfo.EXTRA_NICK_NAME);
                    userInfo.popValue = DBUtil.getInt(c, BaseUserInfo.EXTRA_POP_VALUE);
                    userInfo.privatePhotoIds = DBUtil.getString(c, BaseUserInfo.EXTRA_PRIVATE_PHOTO_IDS);
                    userInfo.publicPhotoIds = DBUtil.getString(c, BaseUserInfo.EXTRA_PUBLIC_PHOTO_IDS);
                    userInfo.role = DBUtil.getInt(c, BaseUserInfo.EXTRA_ROLE);
                    userInfo.sign = DBUtil.getString(c, BaseUserInfo.EXTRA_SIGN);
                    userInfo.uid = DBUtil.getLong(c, BaseUserInfo.EXTRA_UID);
                    userInfo.weight = DBUtil.getInt(c, BaseUserInfo.EXTRA_WEIGHT);
                    userInfo.visitTimes = DBUtil.getString(c, BaseUserInfo.EXTRA_VISIT_TIMES);
                    userInfo.money = DBUtil.getInt(c, BaseUserInfo.EXTRA_MONEY);
                    userInfo.visitorIds = DBUtil.getString(c, BaseUserInfo.EXTRA_VISITOR_IDS);
                    userInfo.accountName = DBUtil.getString(c, BaseUserInfo.EXTRA_ACCOUNT_NAME);
                    userInfo.interestModifyTime = DBUtil.getLong(c, BaseUserInfo.EXTRA_ATTENTION_MODIFY_TIME);
                    userInfo.privateAlbumModifyTime = DBUtil.getLong(c, BaseUserInfo.EXTRA_PRIVATE_ALBUM_MODIFY_TIME);
                    userInfo.shareModifyTime = DBUtil.getLong(c, BaseUserInfo.EXTRA_SHARE_MODIFY_TIME);
                    userInfo.myFansCount = DBUtil.getInt(c, BaseUserInfo.EXTRA_MY_FANS_COUNT);
                    userInfo.blackModifyTime = DBUtil.getLong(c, BaseUserInfo.EXTRA_BLACK_MODIFY_TIME);
                }
                c.close();
            }
            if(!MainTabActivity.isAppShowing){
                close();
            }
            return userInfo;
        }
    }
    
    public static final int DATA_TYPE_STRING = 0;
    public static final int DATA_TYPE_INT = 1;
    public static final int DATA_TYPE_LONG = 2;
    
    public static String getUserInfoSingleColumn(Context context, long uid, String column, int dataType){
        initDB(context);
        synchronized (mSqLiteDatabase) {
            if(!mSqLiteDatabase.isOpen()){
                return null;
            }
            String str = null;
            Cursor c = mSqLiteDatabase.query(BaseUserInfo.TABLE_NAME, new String[]{column}, BaseUserInfo.EXTRA_UID + "=?", new String[]{String.valueOf(uid)}, null, null, null);
            if (null != c) {
                if (c.getCount() == 1 && c.moveToFirst()) {
                    switch (dataType) {
                    case DATA_TYPE_STRING:
                        str = DBUtil.getString(c, column);
                        break;

                    case DATA_TYPE_INT:
                        str = String.valueOf(DBUtil.getInt(c, column));
                        break;
                        
                    case DATA_TYPE_LONG:
                        str = String.valueOf(DBUtil.getLong(c, column));
                        break;
                    }
                    
                }
                c.close();
            }
            if(!MainTabActivity.isAppShowing){
                close();
            }
            return str;
        }
    }
    
    public static void close() {
        if (null != mSqLiteDatabase) {
            synchronized (mSqLiteDatabase) {
                mSqLiteDatabase.close();
                if (null != mGeeSQLite) {
                    mGeeSQLite.close();
                }
                SQLiteDatabase.releaseMemory();
            }
        }
    }
    
}
